/*
 * Copyright 2015 Hongxin Telecommunication Technologies Co, Ltd.,
 * Wuhan, Hubei, China. All rights reserved.
 */
package com.hxrd.collect;

/**
 *
 * @author chenwei Created on 2016-12-22, 19:14:49
 */
import com.hxrd.Luncher;
import com.hxrd.data.Device;

import java.io.*;
import java.util.Properties;

import com.jcraft.jsch.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CmdCollect
{
	private static Log log = LogFactory.getLog(CmdCollect.class);
	private JSch jsch = new JSch();
	private Session session = null;

	public boolean connect(String ip, String user, String passwd, int port)
	{
		try
		{
			session = jsch.getSession(user, ip, port);
			session.setTimeout(Luncher.sessionTimeout*1000);
		}
		catch(JSchException e)
		{
			// TODO Auto-generated catch block
			log.info("get Session failed...");
			e.printStackTrace();
			return false;
		}
		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		session.setConfig(config);
		session.setPassword(passwd);
		try
		{
			session.connect();
			if(session.isConnected()){
				System.out.println("connect");
			}
		}
		catch(JSchException e)
		{
			// TODO Auto-generated catch block
//			e.printStackTrace();
			log.info("connect fail:"+ip);
			return false;
		}
		return true;
	}

	public boolean connect(Device dev)
	{
		return connect(dev.getIp(), dev.getUsername(),
				dev.getPassword(), 22);
	}

	public boolean shellCommand(Device dev)
	{
		if(!connect(dev))
		{
			return false;
		}

		Channel channel = null;
		try
		{
			channel = session.openChannel("shell");
			channel.connect(Luncher.commandTimeout*1000);//change command execute time 1s->2s
			OutputStream outstream = null;
			try
			{
				outstream = channel.getOutputStream();
			}
			catch(IOException e)
			{
				// TODO Auto-generated catch block
				log.info("open shell fail:"+dev.getIp());
				return false;
			}

			execmd(outstream, channel, "en");
			execmd(outstream, channel, "conf t");
			execmd(outstream, channel, "conf snmp");
			execmd(outstream, channel, "snmp service enable");

			Thread.sleep(5000);
			// 返回的结果可能是标准信息,也可能是错误信息,所以两种输出都要获取
			// 一般情况下只会有一种输出.
			// 但并不是说错误信息就是执行命令出错的信息,如获得远程java JDK版本就以
			// ErrStream来获得.
			outstream.close();

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			channel.disconnect();
			session.disconnect();
		}
		return true;
	}

	private boolean execmd(OutputStream outstream, Channel channel, String cmd) throws Exception
	{
		// 执行的SHELL命令，需要用\n结尾，表示回车
		outstream.write((cmd + "\n").getBytes());
		outstream.flush();
		Thread.sleep(Luncher.commandSleep*1000);//change command execute time 1s->2s
		return true;
	}

	public String sendCommand(String command)
	{
		StringBuilder outputBuffer = new StringBuilder();
		try
		{
			/*
			Channel channel = session.openChannel("exec");
			((ChannelExec)channel).setCommand(command);
			channel.setInputStream(null);
			InputStream commandOutput = channel.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(commandOutput));
			channel.connect();
			*/
			ChannelShell channel = (ChannelShell) session.openChannel("shell");
			channel.connect();
			InputStream inputStream = channel.getInputStream();
			OutputStream outputStream = channel.getOutputStream();
			outputStream.write(command.getBytes());
			outputStream.flush();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));

			String msg;
			while((msg = in.readLine())!=null){
				System.out.println(msg);
				outputBuffer.append(msg);
			}
			in.close();



//			int readByte = commandOutput.read();
//			String lido;
//			while ((lido = reader.readLine()) != null) {
//				outputBuffer.append(lido);
//			}
//			while(readByte != 0xffffffff)
//			{
//				outputBuffer.append((char)readByte);
//				readByte = commandOutput.read();
//			}
//			channel.disconnect();
		}
		catch(IOException ioX)
		{
			System.out.println(ioX.getMessage());
			return null;
		}
		catch(JSchException jschX)
		{
			System.out.println(jschX.getMessage());
			return null;
		}
		return outputBuffer.toString();
	}


}
